package com.egg.ylt.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.fragment.FRA_Center;
import com.egg.ylt.pojo.BindEquipmentEntity;
import com.egg.ylt.presenter.impl.ScanCodePresenterImpl;
import com.egg.ylt.view.IScanCodeView;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.ToastUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ACT_ScanCode extends BaseActivity<ScanCodePresenterImpl> implements IScanCodeView {


    @BindView(R.id.fl_scan_view)
    FrameLayout flScanView;
    @BindView(R.id.btn_put_code)
    TextView btnPutCode;
    @BindView(R.id.iv_scan_back)
    ImageView ivScanBack;

    // 拍照回传码
    public final static int CAMERA_REQUEST_CODE = 0;

    private AppSharedPreferences mSp;

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_scan_code;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
        mSp = new AppSharedPreferences(mContext);
        //初始化扫描界面
        initScanView();
    }

    private void initScanView() {
        //打开相机的动态权限
        requestPhotosPermissions();
        //执行扫面Fragment的初始化操作
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);

        captureFragment.setAnalyzeCallback(analyzeCallback);
        //替换我们的扫描控件
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_scan_view, captureFragment).commit();
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            mPresenter.setBind(Constants.TOKEN, result, Constants.COMPANYID, "");
//            Intent resultIntent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
//            bundle.putString(CodeUtils.RESULT_STRING, result);
//            resultIntent.putExtras(bundle);
//            ACT_ScanCode.this.setResult(RESULT_OK, resultIntent);
//            ACT_ScanCode.this.finish();
        }

        @Override
        public void onAnalyzeFailed() {
            ToastUtil.makeText(mContext, "解析二维码失败", false);
//            Intent resultIntent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
//            bundle.putString(CodeUtils.RESULT_STRING, "");
//            resultIntent.putExtras(bundle);
//            ACT_ScanCode.this.setResult(RESULT_OK, resultIntent);
//            ACT_ScanCode.this.finish();
        }
    };

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }


    @OnClick({R.id.iv_scan_back, R.id.btn_put_code})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_scan_back://返回
                finish();
                break;
            case R.id.btn_put_code://去输入设备号
                readyGo(ACT_InputFacilityNumber.class);
                break;
        }
    }

    /**
     * 点击拍照,动态申请权限
     */
    public void requestPhotosPermissions() {
        //第二个参数是需要申请的权限
        if (ContextCompat.checkSelfPermission(mContext,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 进入这儿表示没有权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, Manifest.permission.CAMERA)) {
                // 提示已经禁止
                ToastUtil.makeText(mContext, "已经禁止打开相机", false);
            } else {
                //权限还没有授予，需要在这里写申请权限的代码
                // 第二个参数是一个字符串数组，里面是你需要申请的权限 可以设置申请多个权限
                // 最后一个参数是标志你这次申请的权限，该常量在onRequestPermissionsResult中使用到
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                        CAMERA_REQUEST_CODE);
            }

        } else { //权限已经被授予，在这里直接写要执行的相应方法即可

        }
    }

    /**
     * 权限申请回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            } else {
                // Permission Denied
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    public void setBindFacility(BindEquipmentEntity entity) {
        if (entity == null){
            return;
        }
        mSp.putString(Constants.BABY_ID, entity.getBabyId());
        mSp.putString(Constants.SWIM_RING_ID, entity.getCode());
        finish();
    }

    @Override
    public void getScanFailure() {
        //扫码失败
        finish();
    }

}
